package com.bytedy.sboot.api.controller;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.bytedy.sboot.support.dto.LoginResult;
import com.bytedy.sboot.support.dto.LoginUserDTO;

import jakarta.annotation.Resource;

@RestController
public class LoginController {

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Object login(@RequestBody LoginUserDTO user) {

        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(
                user.getUsername(),
                user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authRequest);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
    
        var result = new LoginResult();
        result.setUsername(user.getUsername());
        result.setAuthorities(authenticate.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList());
        return result;
    }

}
